package fa7.socialcode.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import fa7.socialcode.dao.ComentarioDao;
import fa7.socialcode.model.Comentario;

public class ComentarioDaoJpa implements ComentarioDao {
	
	private static EntityManagerFactory factory;
	static {
		factory = Persistence.createEntityManagerFactory("socialcode");
	}

	private EntityManager entityManager;

	private EntityManager getEntityManager() {
		if (entityManager == null)
			entityManager = factory.createEntityManager();
		return entityManager;

	}

	public List findComentarios() {
		return getEntityManager().createQuery("from Comentario")
				.getResultList();
	}

	public void removeComentario(Comentario comentario) {
		getEntityManager().getTransaction().begin();

		getEntityManager().remove(comentario);

		getEntityManager().getTransaction().commit();
	}

	public void removeComentario(Long id) {
		getEntityManager().getTransaction().begin();

		getEntityManager().remove(findComentario(id));

		getEntityManager().getTransaction().commit();
	}

	public void saveComentario(Comentario comentario) {
		getEntityManager().getTransaction().begin();
		if (comentario.getId() != null) {
			getEntityManager().merge(comentario);
		} else {
			getEntityManager().persist(comentario);
		}

		getEntityManager().getTransaction().commit();
	}

	public Comentario findComentario(Long id) {
		return getEntityManager().find(Comentario.class, id);
	}

}
